package com.ms.controller.user;

import com.ms.constant.MessageConstant;
import com.ms.domain.dto.ChangePasswordDTO;
import com.ms.domain.dto.ForgetPasswordDTO;
import com.ms.domain.dto.UserLoginDTO;
import com.ms.domain.dto.UserProfileUpdateDTO;
import com.ms.domain.entity.User;
import com.ms.domain.vo.UserLoginVO;
import com.ms.domain.vo.UserVO;
import com.ms.exception.AccountNotFoundException;
import com.ms.result.Result;
import com.ms.service.UserService;
import com.ms.utiles.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/user")
@Slf4j
@Tag(name = "C端用户相关接口")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户登录
     *
     * @param userLoginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录接口")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        try {
            User user = userService.login(userLoginDTO);

            // 生成JWT令牌
            String token = jwtUtil.createUserToken(user.getId());

            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .nickname(user.getNickname())
                    .password(user.getPassword())
                    .role(user.getRole())
                    .token(token)
                    .build();

            return Result.success(userLoginVO);
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.badRequest(MessageConstant.LOGIN_FAILED);
        }
    }

    /**
     * 用户登出
     */
    @GetMapping("/logout")
    @Operation(summary = "用户登出接口")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 用户注册
     *
     * @param userLoginDTO 用户注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册接口")
    public Result<String> register(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户注册：{}", userLoginDTO);
        try {
            userService.register(userLoginDTO);
            return Result.success();
        } catch (Exception e) {
            return Result.badRequest(e.getMessage());
        }
    }

    /**
     * 用户忘记密码
     *
     * @param forgetPasswordDTO 用户忘记密码信息
     * @return 忘记密码结果
     */
    @PostMapping("/resetPassword")
    @Operation(summary = "用户忘记密码接口")
    public Result<String> resetPassword(@RequestBody ForgetPasswordDTO forgetPasswordDTO) {
        log.info("用户忘记密码：{}", forgetPasswordDTO);
        // 约定：忘记密码重置密码，DTO中只包含用户名、新密码，旧密码为空
        try {
            userService.forgetPassword(forgetPasswordDTO);
            return Result.success();
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.badRequest(e.getMessage());
        }
    }

    /**
     * 根据id获取用户信息
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "通过id获取用户信息接口")
    public Result<UserVO> getUserInfoById(@PathVariable Integer id) {
        log.info("通过id获取用户信息：{}", id);
        try {
            return Result.success(userService.getUserInfoById(id));
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 根据昵称获取用户信息，用于搜索
     *
     * @param nickname 昵称
     * @return 用户信息
     */
    @GetMapping("/getUserInfoByNickName")
    @Operation(summary = "根据昵称获取用户信息")
    public Result<User> getUserInfoByNickName(String nickname) {
        log.info("根据昵称获取用户信息：{}", nickname);
        try {
            return Result.success(userService.getUserInfoByNickName(nickname));
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 获取所有用户信息
     *
     * @return
     */
    @GetMapping("/getAllUsers")
    @Operation(summary = "获取所有用户信息")
    public Result<List<User>> getAllUsers() {
        return Result.success(userService.getAllUsers());
    }

    /**
     * 更新用户个人信息
     *
     * @param userProfileUpdateDTO 用户个人信息
     * @return 更新结果
     */
    @PutMapping("/profile")
    @Operation(summary = "修改用户信息接口")
    public Result<String> updateUserInfo(@RequestBody UserProfileUpdateDTO userProfileUpdateDTO,
                                         @RequestPart MultipartFile avatarFile,
                                         @RequestPart MultipartFile backgroundFile) {
        log.info("修改用户信息：{}", userProfileUpdateDTO + avatarFile.toString() + backgroundFile.toString());
        try {
            userService.updateUserInfo(userProfileUpdateDTO, avatarFile, backgroundFile);
            return Result.success();
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.badRequest(e.getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @param changePasswordDTO 修改密码信息
     * @return 修改结果
     */
    @PutMapping("/changePassword")
    @Operation(summary = "用户修改密码接口")
    public Result<String> changePassword(@RequestBody ChangePasswordDTO changePasswordDTO) {
        log.info("修改密码：{}", changePasswordDTO);
        try {
            userService.changePassword(changePasswordDTO);
            return Result.success();
        } catch (AccountNotFoundException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.badRequest(e.getMessage());
        }
    }
}